<?php
namespace Home\Controller;

use Home\Org\Util\TTXApi;
use Home\Org\Util\Sqlserver;

/**
 * 仓库模块
 * 
 * @author dem
 *        
 */
class WarehouseController extends HomeController
{
    public $company = 'HYW';
    function index()
    {

        $this->display('Report/index');
    }

    /**
     * 出
     */
    function out()
    {
        $this->display();
    }

    /**
     * 出库操作
     */
    function saveout()
    {
        import("@.ORG.Util.TTXApi");
        $postData = json_decode(I('data'), 1);
        $CardCode = I('CardCode');
        $data = array();
        $totalQty = 0;
        foreach ($postData as $key => $vo) {
            $totalQty += $vo['ItemCount'];
            $data[$key] = array(
                'Erporderlinenum' => $key,
                'Polineid'=>$key,
                'Item' => $vo['Item'],
                'ItemName' => $vo['ItemName'],
                'ItemCount' => $vo['ItemCount'],
                'Sprice' => $vo['Sprice'],
                'Lot' => '',
                'InventorySts'=>$vo['InventorySts'], //可售   A07 样品 106残次品
                
            );
        }
        
        $totalLines = count($data);
        $shipmentId = 'OA' . time();
        $shipmentType = I('type');
        $wcode = I('wcode');
        $remark = I('remark');
        $carrier = I('Carrier');
        $name = I('name');
        $state = I('State');
        $city = I('City');
        $address = I('Address');
        $District = I('District');
        $ShipmentNote = I('ShipmentNote');
        $phone  = I('phone');
        $torderCode = I('TorderCode');
        $headArr = array(
            'Company' => $this->company,
            'WareHouse' => $wcode ?  : 'HYWCK',
            'TotalQty' => $totalQty,
            'TotalLines' => $totalLines,
            'ShipmentId' => $shipmentId,
            'SHIP_FROM'=>$CardCode,
            'TorderCode' => $torderCode?:$shipmentId, // ERP订单号
            'EbillNumber' => '', // 电子面单 N
            'BigChar' => '', // 大头笔/格口号 N
            'ShipmentType' => $shipmentType,
            'Carrier' => $carrier, // 承运商代码 快递公司 N
            'TrackingNumber'=>'',
            'Name' => $name, // 收货人 N
            'PostCode' => '',
            'Phone' => '',
            'Mobile' => $phone,
            'State' => $state, // 收货人地址
            'City' => $city, // 市
            'District' => $District,//县
            'Address' => $address, // 收货详细地址
            'ShopName'=>'',//店铺
            'DeliveryNote'=>'',//配送要求
            'ShipmentNote'=>$ShipmentNote,//备注
            'CheckDate'=>date('Y-m-d H:i:s'),
            'ShipDate' => date('Y-m-d'),
            'Cod' => 'N',
            'CodValue' => '0',
            'Userdef1'=>'N',
            'Userdef2'=>'u2',
            'Userdef3'=>'u3',
            'Userdef4'=>'u4'
            
        );
        
        $xmlStr = TTXApi::createXML('ShipmentRequest', $headArr, $data);
        $sign  = TTXApi::getTTXSign('ShipmentRequest', $xmlStr,$this->company);
        $res = TTXApi::http('ShipmentRequest',  $this->company, $xmlStr, $sign, false, true);
        if ($res['Success']) {
            // 请求wms系统并处理成功
            $m = M('ReceiptRequest');
            $item_m = M('ReceiptRequestItems');
            $headArr['ctime'] = time();
            $headArr['emp_no'] = session('emp_no');
            $headArr['data_type'] = 2;
            $headArr['ReceiptId'] = $headArr['ShipmentId'];
            $headArr['ReceiptType'] = $headArr['ShipmentType'];
            $pid = $m->add($headArr);
            unset($headArr);
            foreach ($data as $save) {
                $save['pid'] = $pid;
                $item_m->add($save);
            }
            
            unset($data);
        }
        TTXApi::log(__FUNCTION__,$xmlStr, json_encode($res,1));
        
        echo json_encode($res);
    }

    /**
     * 入库
     */
    function enter()
    {
        $this->display();
    }

    /**
     * 入库操作
     */
    function saveenter()
    {
        import("@.ORG.Util.TTXApi");
        $postData = json_decode(I('data'), 1);
        $data = array();
        $totalQty = 0;
        foreach ($postData as $key => $vo) {
            $totalQty += $vo['ItemCount'];
            $data[$key] = array(
                'Polineid' => $key,
                'Item' => $vo['Item'],
                'ItemName' => $vo['ItemName'],
                'ItemCount' => $vo['ItemCount'],
                'Sprice' => $vo['Sprice'],
                'Lot' => 'testlot'
            );
        }
        $totalLines = count($data);
        $receiptId = 'OA' . time();
        $ReceiptType = I('type');
        $wcode = I('wcode');
        $remark = I('remark');
        $CardCode = I('CardCode');
        $CardName = I('CardName');
        $headArr = array(
            'Company' => 'HYW',
            'WareHouse' => $wcode ?  : 'HYWCK',
            'TotalQty' => $totalQty,
            'TotalLines' => $totalLines,
            'ReceiptId' => $receiptId,
            'ReceiptType' => $ReceiptType,
            'OrderDate' => date('Y-m-d'),
            'Remark' => $remark,
            'SHIP_FROM'=>$CardCode,
            'SHIP_FROM_NAME'=>$CardName,
            
            
        );
        $xmlStr = TTXApi::createXML('ReceiptRequest', $headArr, $data);
        $sign  = TTXApi::getTTXSign('ReceiptRequest', $xmlStr,$this->company);
        //error_log($xmlStr);
        $res = TTXApi::http('ReceiptRequest', $this->company, $xmlStr, $sign, false, true);
        if ($res['Success']) {
            // 请求wms系统并处理成功
            $m = M('ReceiptRequest');
            $item_m = M('ReceiptRequestItems');
            $headArr['ctime'] = time();
            $headArr['emp_no'] = session('emp_no');
            $headArr['data_type'] = 1;
            $pid = $m->add($headArr);
            unset($headArr);
            foreach ($data as $save) {
                $save['pid'] = $pid;
                $item_m->add($save);
            }
            unset($data);
        }
        TTXApi::log(__FUNCTION__,$xmlStr, json_encode($res,1));
        echo json_encode($res);
    }

    /**
     * 出库类型
     */
    function getShipmentRequestType(){
         import("@.ORG.Util.Sqlserver");
        $sql = "SELECT * from [@AX_INV_IN_OUT_TYPE] where U_IS_INOUT='OUT'";
        $sqlObj = new Sqlserver();
        $data = $sqlObj->query($sql);
        echo json_encode($data);
        exit;
        
    }
    
    /**
     * 查看记录
     */
    function querylist()
    {
        $key = I('keyword');
        $type = I('type');
        $map=[];
        if($type){
            $map['data_type'] = array('eq', $type);
        }
        if($key){
            $map['ReceiptId'] = array('like',  '%' . trim($key) . '%');
        }
        $model = M("ReceiptRequest");
        $res= $this -> _list($model, $map, 'id desc');
        $this->display();
        
    }
    
    
    /***
     * 出入库单详情
     */
    function billdetails(){
        $id = I('id');
        $map=['pid'=>$id];
        $model = M("ReceiptRequestItems");
        $res= $this -> _list($model, $map, 'id desc');
        $this->display();
        
    }
    
    /**
     * 获取供应商列表
     */
    function getSupplier(){
        $key = I('key');
        if($key){
            $where = "AND cardcode like '%{$key}%' or cardname like '%{$key}%'";
        }
        import("@.ORG.Util.Sqlserver");
        $sql = "select cardcode,cardname from ocrd where cardtype='S' $where ";
        $sqlObj = new Sqlserver();
        $data = $sqlObj->query($sql);
        echo json_encode($data);
        exit;
        
    }
    
    /**
     * 导出已发货订单
     */
    function exportOrderExpNo(){
        $this->assign('start',date('Y-m-d',time()-86400).' 00:00:00');
        $this->assign('end',date('Y-m-d H:i:s'));
        $this->display();
    }
    
    /**
     * 运费
     */
    function freight(){
        $this->assign('src', '/sap/freight.php');
        $this->display('report/index');
   
    }
    
    
    function importAjax(){
        set_time_limit(0);
        $File = D('File');
        $file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
        $info = $File -> upload($_FILES, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG"));
        if($info){
            //取得成功上传的文件信息
            Vendor('Excel.PHPExcel');
            //导入thinkphp第三方类库
            $inputFileName = C('DOWNLOAD_UPLOAD.rootPath') . $info['uploadfile']["savepath"] . $info['uploadfile']["savename"];
            $objPHPExcel = \PHPExcel_IOFactory::load($inputFileName);
            $sheetData   = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);
            $count       = count($sheetData);
            $saveData    = array();
            $errorStr    = '';
            $p_id        = D('Expresscostmain')->add(array('CreateDatetime'=>date('Y-m-d H:i:s'),'LastChkDatetime'=>'','DocOwner'=>session('user_name')));
            $model       = D('Expresscostsub');
            $time =  date('Y-m-d H:i:s');
            for ($i = 2; $i <= $count; $i++) {
                $data = array();
                 $data['pid']   = $p_id;
                 $data['ExpNo']    = $sheetData[$i]["A"]; 
                 $data['ExpCom']   = $sheetData[$i]["B"];
                 $data['Weight']   = doubleval($sheetData[$i]["C"]);
                 $data['Cost']     = doubleval($sheetData[$i]["D"]);
                 $data['province'] = $sheetData[$i]["E"];
                 $data['ctime']    = $time;
                 $model->add($data);
            }
     
            echo json_encode(array('code'=>0,'msg'=>'导入成功'),1);
            exit;
        }else{
            echo json_encode(array('code'=>-1,'msg'=>'导入失败'),1);
            exit;
        }
    }
    
    
    function stock(){
        $this->display();
        
    }
    
    
    function getStockData(){

        $itemCode = I('itemCode');
        $dscription = I('dscription');
        $warehouse = I('warehouse');
        $cgy  = I('cgy');
        $docNum = I('docNum');
        $whereStr = '';
        if($itemCode)
            $whereStr.=" AND (T0.[ItemCode] ='{$itemCode}' OR '{$itemCode}'='') ";
        if($dscription)
            $whereStr.=" AND (T0.[ItemName] LIKE N'%{$dscription}%' OR '$dscription'='') ";
        if($warehouse)
            $whereStr.=" AND (T1.[WhsCode] ='{$warehouse}' OR '{$warehouse}'='') ";
        import("@.ORG.Util.Sqlserver");
        $sqlObj = new Sqlserver();
        $sql = "SELECT T0.[ItemCode],T0.[U_IT001] classification,T0.[U_Brand],T0.[U_FWID] , T0.[ItemName], T1.[WhsCode], T1.[OnHand] ,T1.[AvgPrice] ItemCB, (T1.[AvgPrice] * T1.[OnHand]) AS 'TotalCB' FROM OITM T0 INNER JOIN OITW T1 ON T0.ItemCode = T1.ItemCode WHERE T0.[ItemCode] = T1.[ItemCode]  AND T1.[OnHand] >0 AND T0.ITEMCODE LIKE 'B1%' {$whereStr}";
        $sql= iconv("utf-8","gb2312",$sql);
        $data = $sqlObj->query($sql);
        echo json_encode(array('total'=>count($data),'data'=>$data));
        
    }
    
    
    
    
    /**
     * 采购分析
     */
    function receipt(){
        
        $this->display();
    }
    
    function getreceiptData(){
        $start = I('start');
        $end   = I('end');
        $cardName = I('cardName');
        $itemCode = I('itemCode');
        $dscription = I('dscription');
        $cgy  = I('cgy');
        $docNum = I('docNum');
        $DocStatus=I('DocStatus');
        $whereStr = 'WHERE 1=1 ';
        $whereList = array('T0.[CardName]'=>$cardName,'T1.[ItemCode]'=>$itemCode,'T1.[Dscription]'=>$dscription,'T2.[SlpName]'=>$cgy,'T0.[DocNum]'=>$docNum);
        foreach ($whereList as $key=>$where){
            if($where)
                $whereStr.=" AND {$key} LIKE '%{$where}%' ";
        }
        if($start)
            $whereStr.= " AND T0.[DocDate] >='{$start}' ";
        if($end)
            $whereStr.= " AND T0.[DocDate] <='{$end}' ";
        if($DocStatus)
            $whereStr.= " AND (T0.[canceled]+T0.[DocStatus]) ='{$DocStatus}' ";
        
        import("@.ORG.Util.Sqlserver");
        $sqlObj = new Sqlserver();
        $sql = "SELECT (case (T0.[canceled]+T0.[DocStatus]) when 'NO' then '未清' when 'NC' then '已清' when 'YC' then '已取消' else '异常' end) [docstatus], (case T1.LinManClsd when 'Y' then '已关闭' else '未关闭' end) [isClose], T0.[DocNum], T0.[CardCode], T0.[CardName], T0.[NumAtCard],T2.[SlpName][CGY], T0.[TaxDate], T0.[DocDueDate][JHDate], T1.[ItemCode], T1.[Dscription], T1.[Quantity],T1.OPENQTY, T1.[Price][CGPrice], T1.OPENQTY*T1.[Price] [OPENPrice],(T1.[Quantity]-T1.OPENQTY)* T1.[Price] [CLOSEPrice] FROM OPOR T0 INNER JOIN POR1 T1 ON T0.DocEntry = T1.DocEntry INNER JOIN OSLP T2 ON T0.SlpCode = T2.SlpCode {$whereStr}";
        $sql= iconv("utf-8","gb2312",$sql);
        $data = $sqlObj->query($sql);
        echo json_encode(array('total'=>count($data),'data'=>$data));
    }
    
    function  getfreightData(){
        $where = ' where 1=1 ';
        $key = I('key');
        if($key)
            $where .=" and ExpNo like '%{$key}%'";
        $start = I('start');
        $end   = I('end');
        if($start)
            $where .=" and ctime >= '{$start}'";
        
        if($end)
            $where .=" and ctime <= '{$end} 23:59:59'";
        
        $sortOrder = I('sortOrder');
        $sortField = I('sortField')?I('sortField').' '.$sortOrder:" id desc ";
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $countsql = "SELECT count(1) as total from  think_expresscostsub as a {$where} ";
        $limit = ' limit '.($pageIndex*$pageSize).','.$pageSize;
        $quersql = "SELECT * from  think_expresscostsub as a  {$where} order by {$sortField} {$limit} ";
        $model = M('Expresscostsub');
        $total = $model->query($countsql)[0]['total'];
        $res = $model->query($quersql);
        $data = array('total'=>$total,'data'=>$res);
        echo json_encode($data);
        exit;
        
    }
    
    function updatefreightStatus(){
        $ids = rtrim(I('ids'),',');
        if(!$ids){
            echo "请选择要修改的快递单";
            exit;
        }
        $where = "id in ({$ids}) and AvailableCheck!='Y' ";
        if(M('Expresscostsub')->where($where)->save(array('BillStatus'=>'M'))){
            echo '修改成功';
            exit;
        };
        echo '修改失败';
        exit;
    }
}